<?php

define('IN_OS', true);

require(dirname(__FILE__) . '/includes/init.php');
require(ROOT_PATH . '/includes/xajax.common.php');

if ((DEBUG_MODE & 2) != 2)
{
    $smarty->caching = true;
}

/*------------------------------------------------------ */
//-- INPUT
/*------------------------------------------------------ */

/* 获得请求的分类 ID */
if (isset($_REQUEST['cid']))
{
    $cat_id = intval($_REQUEST['cid']);
}
elseif (isset($_REQUEST['id']))
{
    $cat_id = intval($_REQUEST['id']);
}
else
{
    /* 如果分类ID为0，则返回首页 */
    os_header("Location: ./\n");
    exit;
}

/*------------------------------------------------------ */
//-- PROCESSOR
/*------------------------------------------------------ */
/* 页面的缓存ID */
$cache_id = sprintf('%X', crc32($cat_id . '-' . $display . '-' . $sort  .'-' . $order  .'-' . $page . '-' . $size . '-' . $_SESSION['user_rank'] . '-' .
    $_CFG['lang'] .'-'. $brand. '-' . $price_max . '-' .$price_min . '-' . $filter_attr));
if (!$smarty->is_cached('category.dwt', $cache_id))
{
    $children = get_children($cat_id);
    $smarty->assign('imageservice',$_CFG['pre_fetch_img']);
	$smarty->assign('categories',	get_cat_list($children)); // 分类树 get_categories_tree($cat_id,  'goods_detail')
	$smarty->assign('size_list',  get_size_list($children));
	$smarty->assign('color_list',   get_color_list($children));  
	
    if ($brand > 0)
    {
        $arr['all'] = array('brand_id'  => 0,
                        'brand_name'    => '全部商品',
                        'brand_logo'    => '',
                        'goods_num'     => '',
                        'url'           => build_uri('category', array('cid'=>$cat_id))
                    );
    }
    else
    {
        $arr = array();
    }
    
    $brand_list = array_merge($arr,  get_brands($cat_id, 'category'));

    
    /* 获取价格分级 */
    if ($cat['grade'] == 0  && $cat['parent_id'] != 0)
    {
        $cat['grade'] = get_parent_grade($cat_id); //如果当前分类级别为空，取最近的上级分类
    }

    $cat['grade'] = $cat['grade'] < 3?3:$cat['grade'];

    
    /* 需要价格分级 */

    /*
    算法思路：
    1、当分级大于1时，进行价格分级
    2、取出该类下商品价格的最大值、最小值
    3、根据商品价格的最大值来计算商品价格的分级数量级：
    价格范围(不含最大值)    分级数量级
    0-0.1                   0.001
    0.1-1                   0.01
    1-10                    0.1
    10-100                  1
    100-1000                10
    1000-10000              100
    4、计算价格跨度：
    取整((最大值-最小值) / (价格分级数) / 数量级) * 数量级
    5、根据价格跨度计算价格范围区间
    6、查询数据库

    可能存在问题：
    1、
    由于价格跨度是由最大值、最小值计算出来的
    然后再通过价格跨度来确定显示时的价格范围区间
    所以可能会存在价格分级数量不正确的问题
    该问题没有证明
    2、
    当价格=最大值时，分级会多出来，已被证明存在
    */

    $sql = "SELECT min(g.shop_price) AS min, max(g.shop_price) as max ".
    " FROM " . $os->table('goods'). " AS g ".
    " WHERE ($children OR " . get_extension_goods($children) . ') AND g.is_delete = 0 AND g.is_on_sale = 1 AND g.is_alone_sale = 1  ';
    
    //获得当前分类下商品价格的最大值、最小值

    $row = $db->getRow($sql);

    $row['max'] = $row['max'] < 100 ?100:$row['max'];
    
    // 取得价格分级最小单位级数，比如，千元商品最小以100为级数
    $price_grade = 0.0001;
    for($i=-2; $i<= log10($row['max']); $i++)
    {
    	$price_grade *= 10;
    }

    //跨度
    $dx = ceil(($row['max'] - $row['min']) / ($cat['grade']) / $price_grade) * $price_grade;

    if($dx == 0)
    {
    	$dx = $price_grade;
    }

    for($i = 1; $row['min'] > $dx * $i; $i ++);

    for($j = 1; $row['min'] > $dx * ($i-1) + $price_grade * $j; $j++);
    $row['min'] = $dx * ($i-1) + $price_grade * ($j - 1);

    for(; $row['max'] >= $dx * $i; $i ++);
    $row['max'] = $dx * ($i) + $price_grade * ($j - 1);

    $sql = "SELECT (FLOOR((g.shop_price - $row[min]) / $dx)) AS sn, COUNT(*) AS goods_num  ".
    " FROM " . $os->table('goods') . " AS g ".
    " WHERE ($children OR " . get_extension_goods($children) . ') AND g.is_delete = 0 AND g.is_on_sale = 1 AND g.is_alone_sale = 1 '.
    " GROUP BY sn ";

    $price_grade = $db->getAll($sql);

    foreach ($price_grade as $key=>$val)
    {
    	$price_grade[$key]['start'] = $row['min'] + round($dx * $val['sn']);
    	$price_grade[$key]['end'] = $row['min'] + round($dx * ($val['sn'] + 1));
    	$price_grade[$key]['formated_start'] = price_format($price_grade[$key]['start']);
    	$price_grade[$key]['formated_end'] = price_format($price_grade[$key]['end']);
    	$price_grade[$key]['url'] = build_uri('category', array('cid'=>$cat_id, 'bid'=>0, 'price_min'=>$price_grade[$key]['start'], 'price_max'=> $price_grade[$key]['end'], 'filter_attr'=>0));

    	/* 判断价格区间是否被选中 */
    	if (isset($_REQUEST['price_min']) && $price_grade[$key]['start'] <= $price_min && $price_grade[$key]['end'] >= $price_max)
    	{
    		$price_grade[$key]['selected'] = 1;
    	}
    	else
    	{
    		$price_grade[$key]['selected'] = 0;
    	}
    }

    assign_template('c', array($cat_id));

    $position = assign_ur_here($cat_id, $brand_name);
    $smarty->assign('page_title',       $position['title']);    // 页面标题
    $smarty->assign('ur_here',          $position['ur_here']);  // 当前位置
    $smarty->assign('helps',            get_shop_help()); // 网店帮助
    $smarty->assign('price_grade',     $price_grade);
    
    $smarty->assign('brand_list',      $brand_list);

    $smarty->assign('goods_list', get_goods_list($cat_id, $children));	
   
    $smarty->assign('current_cat',  $current_cat);
    assign_dynamic('category'); // 动态内容
	$smarty->assign('best_goods',      get_recommend_goods('best'));    // 推荐商品
    $smarty->assign('keywords',        htmlspecialchars($_CFG['shop_keywords']));
    $smarty->assign('description',     htmlspecialchars($_CFG['shop_desc']));
    	
	$smarty->assign('list_order',           goods_list(list_order($cat_id)));//列表页菜单列表
}

$smarty->display('category.dwt', $cache_id);

function get_size_list($children){
	global $db, $os;
	$sql = "SELECT DISTINCT s.size_id, s.size_code, s.size_name FROM " . $os->table('goods_inventory') . " gi 
	 		JOIN " . $os->table('goods') . " g ON gi.goods_id = g.goods_id LEFT JOIN " . $os->table('size') . 
	 		" s ON gi.size_id = s.size_id WHERE gi.goods_number_available > 0 AND g.is_on_sale = 1 AND g.is_alone_sale = 1 
	 		AND g.is_delete = 0 AND ($children OR " . get_extension_goods($children) . ')';

	return $db->getAll($sql);	
}

function get_color_list($children){
	global $db, $os;
	$sql = "SELECT DISTINCT c.color_id, c.color_code, c.color_name, cl.img_file FROM " . $os->table('goods_inventory') .
	       " as gi,".$os->table('goods') . " as g,".$os->table('color')." as c,".$os->table('goods_color')." as gc, ".$os->table('color_lib')." as cl where gi.goods_id = g.goods_id and gi.color_id = c.color_id and gc.goods_id=gi.goods_id and gc.color_id = c.color_id and gc.img_id=cl.img_id and gi.goods_number_available > 0 AND g.is_on_sale = 1 AND g.is_alone_sale = 1 AND g.is_delete = 0 
	 	   AND ($children OR " . get_extension_goods($children) . ')';
	return $db->getAll($sql);		
}

function get_cat_list($children){
	global $db, $os;            
	$sql = "SELECT DISTINCT ca.cat_id, ca.cat_name FROM " . $os->table('goods_inventory') . " gi 
	 		JOIN " . $os->table('goods') . " g ON gi.goods_id = g.goods_id LEFT JOIN " . $os->table('category') . 
	 		" ca ON g.cat_id =ca.cat_id WHERE gi.goods_number_available > 0 AND g.is_on_sale = 1 AND g.is_alone_sale = 1 
	 		AND g.is_delete = 0 AND ($children OR " . get_extension_goods($children) . ') AND ca.is_show=1 ORDER BY ca.cat_id ASC';
	
	return $db->getAll($sql);		
}
?>